// 导航栏组件
import React from "react";
import { Layout, Dropdown, Menu, Avatar } from "antd";
import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  UserOutlined,
} from "@ant-design/icons";
import { useNavigate } from "react-router";
import { connect } from "react-redux";

const { Header } = Layout;
function TopHeader(props) {
  // console.log(props);
  const {
    role: { roleName },
    username,
  } = JSON.parse(localStorage.getItem("token"));

  const navigate = useNavigate();
  // const [collapsed, setCollapsed] = useState(false);
  const loginOut = () => {
    // 1.移除token
    localStorage.removeItem("token");
    // 2.重定向到登陆页面
    navigate("/login");
  };
  const changeCollapsed = () => {
    // 改变state中 isCollapsed的状态
    // dispatch({})
    // console.log(props);
    props.changeCollapsed();
  };
  const menu = (
    <Menu
      items={[
        {
          key: "1",
          label: roleName,
        },
        {
          key: "2",
          danger: true,
          label: <div onClick={() => loginOut()}>退出登录</div>,
        },
      ]}
    />
  );

  return (
    <Header className="site-layout-background" style={{ padding: "0 16px" }}>
      {props.isCollapsed ? (
        <MenuUnfoldOutlined onClick={() => changeCollapsed()} />
      ) : (
        <MenuFoldOutlined onClick={() => changeCollapsed()} />
      )}
      {/* 浮动 */}
      <div style={{ float: "right" }}>
        <span>欢迎{username}回来</span>
        <Dropdown overlay={menu}>
          <Avatar size={32} icon={<UserOutlined />} />
        </Dropdown>
      </div>
    </Header>
  );
}
/*
connect：用于包装 UI 组件生成容器组件  是一个高阶函数
connect(
  mapStateToProps  //将外部的数据（即state对象）转换为UI组件的标签属性
  mapDispatchToProps //将分发action的函数转换为UI组件的标签属性
)(被包装的组件)
 */
const mapStateToProps = ({ CollApsedReducer: { isCollapsed } }) => {
  // console.log(isCollapsed);
  return {
    isCollapsed,
  };
};
const mapDispatchToProps = {
  changeCollapsed() {
    return {
      type: "change_collapsed",
      // payload
    };
  },
};
export default connect(mapStateToProps, mapDispatchToProps)(TopHeader);
